﻿#include"tools.h"

using namespace std;

string trimAll(string str, string replace) {
	int begin = 0;
	begin = str.find(replace, begin);
	while (begin != -1)
	{
		str.replace(begin, replace.length(), "");
		begin = str.find(" ", begin);
	}
	return str;
}


//去掉首位空格
string trim(string s)
{
	if (s.empty())
	{
		return s;
	}
	s.erase(0, s.find_first_not_of(" "));
	s.erase(s.find_last_not_of(" ") + 1);
	return s;
}

bool FileExist(const char *filename)
{
	return (_access(filename, 0) == 0);
}


vector<string>split(string str, string token) {
	vector<string>result; int pos = 0;
	while ((pos = str.find(token)) != -1) {
		result.push_back(str.substr(0, pos));
		str = str.substr(pos + token.length(), str.length() - pos - token.length());
	}
	result.push_back(str);
	return result;
}


bool ReadSqlFile(string path, MessagePro &pro) {
	path = trim(path);
	if (!FileExist(path.c_str())) {
		cout << "Can open " + path + " !" << endl;
		return true;
	}
	ifstream fin(path, std::ios::in);
	char line[1024] = { 0 };
	string temp = "";
	while (fin.getline(line, sizeof(line)))
	{
		temp += line;
		if (temp.length() == 0)
			continue;
		if (temp.at(temp.length() - 1) == ';') {
			temp = temp.substr(0, temp.length() - 1);
			cout << "sql->" << temp << endl;
			pro.SendMsg(temp.c_str());
			temp = "";
			if (!pro.ReceiveMsg()) {
				cout << "服务器连接断开！" << endl;
				return false;
			}
		}
		memset(line, 0, 1024);
	}
	return true;
}